package io.github.biezhi.elves.mapper;

import java.math.BigDecimal;
import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import io.github.biezhi.elves.model.CompAnnualReports;
import io.github.biezhi.elves.qcc.model.CompAnalysis;
import io.github.biezhi.elves.qcc.model.CompBasic;
import io.github.biezhi.elves.qcc.model.CompBasicInfo;
import io.github.biezhi.elves.qcc.model.CompChangeRecord;
import io.github.biezhi.elves.qcc.model.CompQccCrawl;
import io.github.biezhi.elves.qcc.model.CompQuota;
import io.github.biezhi.elves.qcc.model.OutboundInvestment;

public interface QccMapper {

	/**
	 * 查询未爬取的工商企业，即IS_SPIDER=0
	 * @return
	 */
//	@Select("select id as compId,ENTNAME as compName from e_baseinfo_zs_2019 where IS_SPIDER = 0 limit #{num}")
	@Select("select cb.id as compId,cb.compName from t_comp_butie cb where cb.isUpdate = 0 limit #{num}")
	public List<CompBasic> queryCompBasic(Integer num);
	
	/**
	 * 根据compId更新爬取状态
	 * @param compId
	 */
//	@Update("update t_comp_basic_zq_qcc set IS_SPIDER=1 where COMP_ID=#{compId}")
//	@Update("update e_target_customer set IS_SPIDER=1 where id=#{compId}")
//	@Update("update e_baseinfo_zs_2019 set IS_SPIDER=1 where id=#{compId}")
	@Update("update t_comp_butie set isUpdate=1 where id=#{compId}")
	void updateSpiderState(Long compId);

	/**
	 * 将爬取出来的数据存放到数据库表中
	 */
/*	@Insert("INSERT INTO t_comp_qcc_crawl (comp_id,pripid,comp_name, qcc_id, comp_detail_html, comp_detail_async_html, company_businessmap, company_relation, company_muhou, company_guquan) "
			+"VALUES (#{compId},#{pripid},#{compName}, #{qccId}, #{compDetailHtml}, #{compDetailAsyncHtml}, #{companyBusinessmap},  #{companyRelation}, #{companyMuhou}, #{companyGuquan})")*/
//	@Insert("INSERT INTO t_comp_qcc_crawl_temp (comp_id,comp_name, qcc_id, comp_detail_html, comp_detail_async_html, company_businessmap, company_relation, company_muhou, company_guquan) "
//			+"VALUES (#{compId},#{compName}, #{qccId}, #{compDetailHtml}, #{compDetailAsyncHtml}, #{companyBusinessmap},  #{companyRelation}, #{companyMuhou}, #{companyGuquan})")
	@Insert("INSERT INTO t_comp_qcc_crawl_butie_2019_tmp (comp_id,comp_name, qcc_id, comp_detail_html, comp_detail_async_html, company_businessmap, company_relation, company_muhou, company_guquan) "
			+"VALUES (#{compId},#{compName}, #{qccId}, #{compDetailHtml}, #{compDetailAsyncHtml}, #{companyBusinessmap},  #{companyRelation}, #{companyMuhou}, #{companyGuquan})")
	@Options(keyColumn = "id", keyProperty = "id", useGeneratedKeys = true)
	public void insertSpiderData(CompQccCrawl compQccCrawl);
	
//	===============================解析企查查HTML页面==================================
	/**
	 * 查询未解析(即is_resolve=0)的CompQccCrawl
	 * @param num 查询数量
	 * @return
	 */
	@Select("select comp_id as compId,pripid as pripid,comp_name as compName, qcc_id as qccId, comp_detail_html as compDetailHtml, "
			+ "comp_detail_async_html as compDetailAsyncHtml, company_businessmap as companyBusinessmap, "
			+ "company_relation as companyRelation, company_muhou AS companyMuhou, company_guquan AS companyGuquan "
			+ "from t_comp_qcc_crawl1 where is_resolve=0 and qcc_id!='' limit #{num} ")
	public List<CompQccCrawl> queryCompQccCrawl(Integer num);
	
	/**
	 * 已经解析过的数据，根据compId将is_resolve更新为1
	 * @param compId
	 */
	@Update("update t_comp_qcc_crawl1 set is_resolve=1 where COMP_ID=#{compId}")
	public void updateResolveState(Long compId);
	
	/**
	 * 将解析出来的基础数据存放到数据库表中
	 */
	@Insert("INSERT INTO t_comp_analysis (comp_id,comp_name, qcc_id, comp_logo, comp_phone, comp_site,"
			+ " comp_email, comp_address, comp_desc,legal_information,regcap,regcap_text,reccap,"
			+ "reccap_text,status,estdate,unified_social_credit_code,taxpayer_ident_number,"
			+ "registration_number,organization_code,company_type,industry_name,apprdate,regorg,"
			+ "country,country_en,name_used,persons_number,personnel_scale,business_term,opscope) "
			+"VALUES (#{compId},#{compName}, #{qccId}, #{compLogo}, #{compPhone}, #{compSite},  "
			+ "#{compEmail}, #{compAddress}, #{compDesc},#{legalInformation},#{regcap}, #{regcapText},"
			+ " #{reccap}, #{reccapText}, #{status},  #{estdate}, #{unifiedSocialCreditCode}, "
			+ "#{taxpayerIdentNumber},#{registrationNumber},#{organizationCode},#{companyType},"
			+ "#{industryName},#{apprdate},#{regorg},#{country},#{countryEn},#{nameUsed},#{personsNumber},"
			+ "#{personnelScale},#{businessTerm},#{opscope})")
	@Options(keyColumn = "id", keyProperty = "id", useGeneratedKeys = true)
	public void insertCompAnalysis(CompAnalysis compAnalysis);
	
	/**
	 * 将解析出来的企业变更记录数据存放到数据库表中
	 */
	@Insert("INSERT INTO t_comp_change_record (comp_id,comp_name, qcc_id, date_change, prj_change, before_change, after_change,historical_change_page) "
			+"VALUES (#{compId},#{compName}, #{qccId}, #{dateChange}, #{prjChange}, #{beforeChange},  #{afterChange},#{historicalChangePage})")
	@Options(keyColumn = "id", keyProperty = "id", useGeneratedKeys = true)
	public void insertCompChangeRecord(CompChangeRecord compChangeRecord);
	
	/**
	 * 将解析出来的企业对外投资数据存放到数据库表中
	 */
	@Insert("INSERT INTO t_outbound_investment (comp_id,comp_name, qcc_id, invested_comp_name, invested_legal, regcap_text,investment_rate,estdate,status,outbound_investment_page) "
			+"VALUES (#{compId},#{compName}, #{qccId}, #{investedCompName}, #{investedLegal}, #{regcapText},  #{investmentRate},#{estdate},#{status},#{outboundInvestmentPage})")
	@Options(keyColumn = "id", keyProperty = "id", useGeneratedKeys = true)
	public void insertOutboundInvestment(OutboundInvestment outboundInvestment);
	
	/**
	 * 将解析出来的图谱数据存放到数据库表中
	 */
	@Insert("INSERT INTO t_comp_basic_info (comp_id,pripid,comp_name, qcc_id, comp_atlas, investment_genealogy, correlation_map,ownership_structure_chart) "
			+"VALUES (#{compId},#{pripid},#{compName}, #{qccId}, #{compAtlas}, #{investmentGenealogy}, #{correlationMap},  #{ownershipStructureChart})")
	@Options(keyColumn = "id", keyProperty = "id", useGeneratedKeys = true)
	public void insertCompBasicInfo(CompBasicInfo compBasicInfo);

	/**
	 * 查询企业变更记录表
	 * @param qccId
	 * @return
	 */
	@Select("select comp_id as compId,comp_name as compName,qcc_id as qccId,date_change as dateChange,"
			+ "prj_change as prjChange,before_change as beforeChange,after_change as afterChange,"
			+ "historical_change_page as historicalChangePage from t_comp_change_record "
			+ "where qcc_id = #{qccId}")
	public List<CompChangeRecord> queryCompChangeRecord(String qccId);

	/**
	 * 查询对外投资表
	 * @param qccId
	 * @return
	 */
	@Select("select comp_id as compId,comp_name as compName,qcc_id as qccId,invested_comp_name as investedCompName,"
			+ "invested_legal as investedLegal,regcap as regcap,regcap_text as regcapText,investment_rate as investmentRate,"
			+ "estdate as estdate,status as status,outbound_investment_page as outboundInvestmentPage "
			+ " from t_outbound_investment where qcc_id = #{qccId}")
	public List<OutboundInvestment> queryOutboundInvestment(String qccId);

	/**
	 * 查询解析后企业信息表
	 * @param qccId
	 * @return
	 */
	@Select("select comp_id as compId,comp_name as compName, qcc_id as qccId, comp_logo as compLogo, "
			+ "comp_phone as compPhone, comp_site as compSite, comp_email as compEmail, "
			+ "comp_address as compAddress, comp_desc as compDesc,legal_information as legalInformation,"
			+ "regcap as regcap,regcap_text as regcapText,reccap as reccap,reccap_text as reccapText,"
			+ "status as status,estdate as estdate,unified_social_credit_code as unifiedSocialCreditCode,"
			+ "taxpayer_ident_number as taxpayerIdentNumber,registration_number as registrationNumber,"
			+ "organization_code as organizationCode,company_type as companyType,industry_name as industryName,"
			+ "apprdate as apprdate,regorg as regorg,country as country,country_en as countryEn,name_used as nameUsed,"
			+ "persons_number as personsNumber,personnel_scale as personnelScale,business_term as businessTerm,opscope as opscope "
			+ " from t_comp_analysis where qcc_id = #{qccId} limit 1")
	public CompAnalysis queryCompAnalysis(String qccId);
	
	/**
	 * 查询年报表
	 * @param pripid
	 * @return
	 */
	@Select("select * from t_comp_annual_reports where pripid = #{pripid}")
	@Results({
		@Result(column = "anche_id", property = "ancheId", id = true),
		@Result(column = "busst_cn", property = "busstCn"),
		@Result(column = "parins_cn", property = "parinsCn"),
		@Result(column = "s_ext_fromnode", property = "sExtFromnode"),
		@Result(column = "s_ext_datatime", property = "sExtDatatime"),
	})
	public List<CompAnnualReports> queryCompAnnualReports(String pripid);

	/**
	 * 查询企业信息表
	 * @param num
	 * @return
	 */
	@Select("select comp_id as compId,pripid as pripid,comp_name as compName,qcc_id as qccId,comp_basic as compBasic,"
			+ "ownership_structure_chart as ownershipStructureChart,outbound_investment as outboundInvestment,"
			+ "historical_change as historicalChange,shareholder_structure as shareholderStructure,investment_genealogy as investmentGenealogy,"
			+ "annual_reports as annualReports,correlation_map as correlationMap,comp_atlas as compAtlas,is_save as isSave "
			+ "from t_comp_basic_info where is_save=0 limit #{num}")
	public List<CompBasicInfo> queryCompBasicInfo(Integer num);

	/**
	 * 更新t_comp_basic_info状态
	 * @param qccId
	 */
	@Update("update t_comp_basic_info set is_save = 1 where qcc_id = #{qccId}")
	public void updateSaveState(String qccId);

	/**
	 * 将处理后的json数据更新到t_comp_basic_info表
	 */
	@Update("update t_comp_basic_info set comp_basic = #{compBasic},outbound_investment=#{outboundInvestment},"
			+ "historical_change=#{historicalChange},annual_reports=#{annualReports} where qcc_id = #{qccId}")
	public void updateJsonData(@Param("compBasic")String compBasic,@Param("outboundInvestment")String outboundInvestment,
			@Param("historicalChange")String historicalChange,@Param("annualReports")String annualReports,@Param("qccId")String qccId);

	/**
	 *  将解析出来的各个企业指标值插入到t_comp_quota表
	 * @param compQuota
	 */
	@Insert("insert into t_comp_quota(comp_id,business_info_count,shareholder_info_count,equity_penetration_map_count,outbound_investment_count,final_beneficiary_count,holding_enterprise_count,leading_member_count,branch_count,company_publicity_count,comp_relation_profile_count,financial_analysis_count,interbank_analysis_count,change_record_count,executed_person_info_count,breach_faith_executed_count,judicial_documents_count,court_notice_count,bulletin_court_count,service_announcement_count,judicial_assistance_count,xingzheng_permit_count,tax_credit_count,bidding_info_count,recruit_count,financial_overview_count,import_export_credit_count,wx_public_number_count,news_public_opinion_count,bulletin_research_report_count,publicity_plots_count,land_transfer_count,goudi_info_count,bond_info_count,spot_check_count,dx_permit_count,supplier_count,customer_count,abnormal_operation_count,serious_illegal_count,equity_pledge_count,xingzheng_punish_count,tax_violation_count,chattel_mortgage_count,environmental_penalties_count,clear_info_count,judicial_auction_count,land_mortgage_count,simple_cancellation_count,publicity_reminder_count,notice_tax_arrears_count,annual_reports_count,financing_info_count,investment_institution_count,core_personnel_count,enterprise_business_count,competing_info_count,private_equity_count,trademark_info_count,patent_info_count,certificate_info_count,copyright_works_count,software_copyright_count,site_info_count) "
			+ "values(#{compId},#{businessInfoCount},#{shareholderInfoCount},#{equityPenetrationMapCount},#{outboundInvestmentCount},#{finalBeneficiaryCount},#{holdingEnterpriseCount},#{leadingMemberCount},#{branchCount},#{companyPublicityCount},#{compRelationProfileCount},#{financialAnalysisCount},#{interbankAnalysisCount},#{changeRecordCount},#{executedPersonInfoCount},#{breachFaithExecutedCount},#{judicialDocumentsCount},#{courtNoticeCount},#{bulletinCourtCount},#{serviceAnnouncementCount},#{judicialAssistanceCount},#{xingzhengPermitCount},#{taxCreditCount},#{biddingInfoCount},#{recruitCount},#{financialOverviewCount},#{importExportCreditCount},#{wxPublicNumberCount},#{newsPublicOpinionCount},#{bulletinResearchReportCount},#{publicityPlotsCount},#{landTransferCount},#{goudiInfoCount},#{bondInfoCount},#{spotCheckCount},#{dxPermitCount},#{supplierCount},#{customerCount},#{abnormalOperationCount},#{seriousIllegalCount},#{equityPledgeCount},#{xingzhengPunishCount},#{taxViolationCount},#{chattelMortgageCount},#{environmentalPenaltiesCount},#{clearInfoCount},#{judicialAuctionCount},#{landMortgageCount},#{simpleCancellationCount},#{publicityReminderCount},#{noticeTaxArrearsCount},#{annualReportsCount},#{financingInfoCount},#{investmentInstitutionCount},#{corePersonnelCount},#{enterpriseBusinessCount},#{competingInfoCount},#{privateEquityCount},#{trademarkInfoCount},#{patentInfoCount},#{certificateInfoCount},#{copyrightWorksCount},#{softwareCopyrightCount},#{siteInfoCount})")
	public void insertCompQuota(CompQuota compQuota);

}
